/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sunspotworld;

import com.sun.spot.core.util.Utils;
import com.sun.spot.ipv6.util.Mutex;
import java.util.Random;

/**
 *
 * @author me
 */
public class Bank {
    private boolean isProtected = true;
    private Mutex mutex = new Mutex();
    private Random generator = new Random();

    public Bank(boolean useProtection) {
        isProtected = useProtection;
    }
    
    int accountBalance;

    public int withdraw(int wAmt){ 
        if (isProtected) {
            mutex.lock();
        }

        int nowBalance = accountBalance;

        System.out.print("Withdraw " +wAmt);
        int newBalance = nowBalance - wAmt;

        System.out.println("...newBalance =  " +newBalance);

        int waitTime = 1 + generator.nextInt(9) * 10;
        Utils.sleep(waitTime);


        accountBalance = newBalance;
        if (isProtected) {
            mutex.unlock();
        }
        return newBalance;
    }
    
    public void deposit(int value) {
        if (isProtected) {
            mutex.lock();
        }

        int nowBalance = accountBalance;

        System.out.print("Deposit " +value);
        int newBalance = nowBalance + value;
        System.out.println("...newBalance =  " +newBalance);

        int waitTime = 1 + generator.nextInt(9) * 10;
        Utils.sleep(waitTime);

        accountBalance = newBalance;

        if (isProtected) {
            mutex.unlock();
        }
    }
}
